<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="计划编号" prop="planCode">
        <el-input v-model="queryParams.planCode" placeholder="请输入计划编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="计划名称" prop="planName">
        <el-input v-model="queryParams.planName" placeholder="请输入计划名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="计划类型" prop="planType">
        <el-select v-model="queryParams.planType" placeholder="请选择类型" clearable>
          <el-option v-for="dict in dict.type.dv_plan_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option v-for="dict in dict.type.check_plan_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['mes:dv:checkplan:add']">新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['mes:dv:checkplan:edit']"
        >修改2</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['mes:dv:checkplan:remove']">删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['mes:dv:checkplan:export']"
        >导出</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="checkplanList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" min-width="55" align="center" />
      <el-table-column type="index" label="序号" align="center" min-width="50" />
      <el-table-column label="计划编码" align="center" prop="planCode" min-width="120">
        <template slot-scope="scope">
          <el-button type="text" @click="handleView(scope.row)">{{scope.row.planCode}}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="计划名称" align="center" min-width="200" prop="planName" />
      <el-table-column label="计划类型" align="center" min-width="120" prop="planType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.dv_plan_type" :value="scope.row.planType" />
        </template>
      </el-table-column>
      <el-table-column label="开始日期" align="center" prop="startDate" min-width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束日期" align="center" prop="endDate" min-width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="周期" align="center" prop="cycleType" min-width="120px">
        <template slot-scope="scope">
          <div style="display: flex;justify-content: center; ">
            <dict-tag :options="dict.type.mes_cycle_type" :value="scope.row.cycleType" />
          </div>

        </template>
      </el-table-column>
      <el-table-column label="处理人" align="center" min-width="120px" prop="handleName" />
      <el-table-column label="每月保养日" align="center" min-width="120px" prop="reminderDay" />
      <el-table-column label="下发时间" align="center" prop="pushTime" min-width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.pushTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.check_plan_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" min-width="130px" fixed="right" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate1(scope.row)" v-hasPermi="['mes:dv:checkplan:remindSet']">提醒设置</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handlePush(scope.row)" v-if="scope.row.status =='1'" v-hasPermi="['mes:dv:checkplan:edit']">下发</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['mes:dv:checkplan:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-if="scope.row.status !='3'" v-hasPermi="['mes:dv:checkplan:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改设备点检计划头对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="960px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="计划编码" prop="planCode">
              <el-input v-model="form.planCode" placeholder="请输入计划编码" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label-width="80">
              <el-switch v-model="autoGenFlag" active-color="#13ce66" active-text="自动生成" @change="handleAutoGenChange(autoGenFlag)" v-if="optType != 'view'">
              </el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划名称" prop="planName">
              <el-input v-model="form.planName" placeholder="请输入计划名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="计划类型" prop="planType">
              <el-select v-model="form.planType" placeholder="请选择计划类型">
                <el-option v-for="dict in dict.type.dv_plan_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="周期" prop="cycleType" label-width="80">
              <el-select v-model="form.cycleType" placeholder="请选择周期">
                <el-option v-for="dict in dict.type.mes_cycle_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="开始日期" prop="startDate">
              <el-date-picker clearable v-model="form.startDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择开始日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="结束日期" prop="endDate">
              <el-date-picker clearable v-model="form.endDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择结束日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" disabled>
                <el-option v-for="dict in dict.type.check_plan_status" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="处理人" prop="handleName">
              <el-autocomplete value-key="userName" v-model="handleName" :fetch-suggestions="querySearchAsync" placeholder="请选择处理人" @select="handleSelectAdmin" @input="(value) => handleInputAdmin(value)"></el-autocomplete>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="每月保养日" prop="reminderDay">
              <el-input-number :min="1" :step="1" v-model="form.reminderDay" placeholder="请输入每月保养日" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-tabs type="border-card" v-if="form.planId != null">
        <el-tab-pane label="设备清单">
          <Checkmachinery ref="machinerylist" :optType="optType" :planId="form.planId"></Checkmachinery>
        </el-tab-pane>
        <el-tab-pane :label="form.planType=='CHECK'?'点检项目':'保养项目'">
          <Checksubject ref="subjectlist" :optType="optType" :planId="form.planId"></Checksubject>
        </el-tab-pane>
      </el-tabs>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="cancel" v-if="optType =='view' || form.status !='1' ">返回</el-button>
        <el-button type="primary" @click="submitForm" v-if="optType !='view' ">保存</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="title" :visible.sync="open1" width="960px" append-to-body>
      <el-form ref="form" :model="form1" :rules="rules1" label-width="100px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="计划编码" prop="planCode">
              <el-input v-model="form1.planCode" placeholder="请输入计划编码" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label-width="80">
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划名称" prop="planName">
              <el-input v-model="form1.planName" placeholder="请输入计划名称" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="每月保养日" prop="reminderDay">
              <el-input-number :min="1" :step="1" v-model="form1.reminderDay" placeholder="请输入每月保养日" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="提醒提前天数" prop="days">
              <el-input-number :min="1" :step="1" v-model="form1.days" placeholder="请输入提醒提前天数" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm1">保存</el-button>
        <el-button @click="cancel1">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCheckplan, getCheckplan, delCheckplan, addCheckplan, updateCheckplan, pushDown } from "@/api/mes/dv/checkplan";
import Checkmachinery from "./machinery.vue"
import Checksubject from "./subject.vue"
import { genCode } from "@/api/mes/md/rule"
import { getAdminList } from "@/api/system/follow";
export default {
  name: "Checkplan",
  dicts: ['mes_cycle_type', 'check_plan_status', 'dv_plan_type'],
  components: { Checkmachinery, Checksubject },
  data() {
    return {
      autoGenFlag: false,
      optType: null,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备点检计划头表格数据
      checkplanList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      open1: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        planCode: null,
        planName: null,
        startDate: null,
        endDate: null,
        cycleType: null,
        cycleCount: null,
        status: null,
        planType: null,
      },
      // 表单参数
      form: {},
      // 表单参数
      form1: {},
      rules1: {},
      // 表单校验
      rules: {
        planCode: [
          { required: true, message: "计划编码不能为空", trigger: "blur" }
        ],
        planName: [
          { required: true, message: "计划名称不能为空", trigger: "blur" }
        ],
        planType: [
          { required: true, message: "计划类型不能为空", trigger: "blur" }
        ],
        cycleType: [
          { required: true, message: "请选择点检周期", trigger: "blur" }
        ],
        cycleCount: [
          { required: true, message: "请输入点检次数", trigger: "blur" }
        ],
        startDate: [
          { required: true, message: "请输入开始日期", trigger: "blur" }
        ],
        endDate: [
          { required: true, message: "请输入结束日期", trigger: "blur" }
        ],
        reminderDay: [
          { required: true, message: "请输入提醒日", trigger: "blur" }
        ],
      },
      adminList: [],
      timeout: null,
      userId: null,
      handleName: null,
    };
  },
  created() {
    this.getList();
    this.getAdminList();
  },
  methods: {
    /** 查询设备点检计划头列表 */
    getList() {
      this.loading = true;
      listCheckplan(this.queryParams).then(response => {
        this.checkplanList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    cancel1() {
      this.open1 = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        planId: null,
        planCode: null,
        planName: null,
        planType: null,
        startDate: null,
        endDate: null,
        cycleType: null,
        cycleCount: null,
        status: "1",
        remark: null,
        attr1: null,
        attr2: null,
        attr3: null,
        attr4: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.autoGenFlag = false;
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.planId)
      this.queryParams.dvCheckPlanIdList = selection.map(item => item.planId);
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.handleName = null;
      this.open = true;
      this.title = "添加计划";
      this.optType = "add";
    },
    // 查询明细按钮操作
    handleView(row) {
      this.reset();
      const planId = row.planId || this.ids;
      getCheckplan(planId).then(response => {
        this.form = response.data;
        this.handleName = this.form.handleName
        this.open = true;
        this.title = "查看计划信息";
        this.optType = "view";
      });
    },
    // 查询明细按钮操作
    handlePush(row) {
      this.reset();
      const planId = row.planId || this.ids;
      pushDown(planId).then(response => {
        this.$modal.msgSuccess("下发成功");
        this.getList();
      }).catch(error => {
        reject(error)
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const planId = row.planId || this.ids
      getCheckplan(planId).then(response => {
        this.form = response.data;
        this.handleName = this.form.handleName
        this.open = true;
        this.title = "修改计划";
        this.optType = "edit";
      });
    },
    handleUpdate1(row) {
      this.reset();
      const planId = row.planId || this.ids
      getCheckplan(planId).then(response => {
        this.form1 = response.data;
        this.open1 = true;
        this.title = "提醒设置";
      });
    },
    submitForm1() {
      updateCheckplan(this.form1).then(response => {
        this.$modal.msgSuccess("设置成功");
        this.open1 = false;
        this.getList();
      }).catch(error => {
        reject(error)
      });
    },
    /** 提交按钮 */
    submitForm() {
      if (this.form.handleId == null) {
        this.$modal.msgError("请选择处理人！");
        return;
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.planId != null) {
            updateCheckplan(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).catch(error => {
              reject(error)
            });
          } else {
            addCheckplan(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).catch(error => {
              reject(error)
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const planIds = row.planId || this.ids;
      this.$modal.confirm('是否确认删除计划编号为"' + row.planCode + '"的数据项？').then(function () {
        return delCheckplan(planIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('mes/dv/checkplan/export', {
        ...this.queryParams
      }, `checkplan_${new Date().getTime()}.xlsx`)
    },
    //自动生成编码
    handleAutoGenChange(autoGenFlag) {
      if (autoGenFlag) {
        genCode('CHECKPLAN_CODE').then(response => {
          this.form.planCode = response;
        });
      } else {
        this.form.planCode = null;
      }
    },
    handleInputAdmin(e) {
      this.userId = null;
    },
    handleSelectAdmin(val) {
      this.form.handleName = val.userName;
      this.form.handleId = val.userId;
      this.userId = val.userId;
    },
    querySearchAsync(queryString, cb) {
      var restaurants = this.adminList;
      var results = queryString
        ? restaurants.filter(this.createStateFilter(queryString))
        : restaurants;
      clearTimeout(this.timeout);
      this.timeout = setTimeout(() => {
        cb(results);
      }, 300 * Math.random());
    },
    createStateFilter(queryString) {
      return (state) => {
        return state.userName.includes(queryString);
      };
    },
    getAdminList() {
      let param = {
        pageNum: 1,
        pageSize: 10000,
      };
      getAdminList(param).then((res) => {
        this.adminList = res.rows ? res.rows : [];
      });
    },
  }
};
</script>
